// pages/register/register.js
const http = require('../../utils/https')

Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    userType: '',
    userTypeIndex: 0,
    userTypeArray: ['患者'],
    loading: false,
    code: '',
    codeUrl: '' // 如果有验证码
  },

  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  onConfirmPasswordInput(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  onUserTypeChange(e) {
    const index = e.detail.value;
    const selectedText = this.data.userTypeArray[index];
    this.setData({
      userTypeIndex: index,
      userType:selectedText
    });
  },

  onCodeInput(e) {
    this.setData({
      code: e.detail.value
    });
  },

  getCode() {
    // 如果有验证码，请求获取验证码图片
    // http.GET('/captchaImage', {}, (res) => {
    //   this.setData({ codeUrl: res.data.img });
    // }, (err) => {
    //   wx.showToast({ title: '获取验证码失败', icon: 'none' });
    // });
  },

  handleRegister() {
    const {
      username,
      password,
      confirmPassword,
      userType
    } = this.data;

    if (!username || !password || !confirmPassword || !userType) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    if (password !== confirmPassword) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      });
      return;
    }

    if (password.length < 5 || password.length > 20) {
      wx.showToast({
        title: '密码长度必须在5到20之间',
        icon: 'none'
      });
      return;
    }

    // 🔁 将中文 userType 转为英文
    let userTypeEn = '';
    if (userType === '患者') {
      userTypeEn = 'patient';
    } else if (userType === '医生') {
      userTypeEn = 'doctor';
    } else {
      wx.showToast({
        title: '用户类型错误',
        icon: 'none'
      });
      return;
    }
    this.setData({
      loading: true
    });

    // 调用注册接口
    http.POST('/register', {
        username,
        password,
        confirmPassword,
        userType: userTypeEn,
        code: '' // 如果有验证码，添加code字段
      },
      (res) => {
        console.log('注册成功:', res);
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });
        // 跳转到登录页面
         wx.navigateTo({ url: '/pages/login/login' });
      },
      (err) => {
        console.error('注册失败:', err);
        wx.showToast({
          title: err.data?.message || '注册失败',
          icon: 'none'
        });
        this.setData({
          loading: false
        });
      }
    );
  },

  goToLogin() {
    wx.navigateBack(); // 或者跳转到登录页 wx.navigateTo({ url: '/pages/login/login' });
  }
});